package jgl.vajra.management.part.vehicle.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.alibaba.fastjson.JSONObject;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import jgl.vajra.management.R;
import jgl.vajra.management.bean.OrderDetailsBean;
import jgl.vajra.management.bean.OrderPaymentDetailsBean;
import jgl.vajra.management.constant.Constant;
import jgl.vajra.management.databinding.ActivityOrderDetailsBinding;
import jgl.vajra.management.dialogFragment.DelayDetailsDialogFragment;
import jgl.vajra.management.event.OrderDelayEvent;
import jgl.vajra.management.event.OrderDetailsCancelEvent;
import jgl.vajra.management.event.PushLatitudeLongitudeEvent;
import jgl.vajra.management.event.PushWorkingProcessEvent;
import jgl.vajra.management.manager.AccountManager;
import jgl.vajra.management.manager.IntentManager;
import jgl.vajra.management.netty.MessageBody;
import jgl.vajra.management.part.home.activity.HomeActivity;
import jgl.vajra.management.part.vehicle.contract.OrderDetailsContract;
import jgl.vajra.management.part.vehicle.viewModel.OrderDetailsViewModel;
import jgl.vajra.management.widget.mvvm.factory.CreateViewModel;
import jgl.vajra.management.widget.mvvm.view.AppActivityManager;
import jgl.vajra.management.widget.mvvm.view.BaseMVVMActivity;
import jgl.vajra.management.widget.retrofithelper.utils.AEACCoder;
import jgl.vajra.management.widget.utils.PhoneUtils;
import jgl.vajra.management.widget.utils.TimeUtils;
import jgl.vajra.management.widget.utils.ToastUtils;
import jgl.vajra.management.widget.utils.UIUtils;

@CreateViewModel(OrderDetailsViewModel.class)
public class OrderDetailsActivity extends BaseMVVMActivity<OrderDetailsViewModel, ActivityOrderDetailsBinding> implements OrderDetailsContract.View {

    private String authorization;
    private String orderId;
    private CountDownTimer timer;
    private OrderPaymentDetailsBean orderPaymentDetailsBean;

    private int waitTime = 0;
    private int cumulativeTime = 0;
    private int restTime = 0;
    private int workTime = 0;
    private BaiduMap mBaiduMap;
    private MapStatus mapBuild;
    private Marker marker;
    private DelayDetailsDialogFragment delayDetailsDialogFragment;

    @Override
    public int getLayoutId() {
        return R.layout.activity_order_details;
    }

    @Override
    public void initView() {
        super.initView();
        mBinding.setView(this);

        authorization = AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization;
        orderId = getIntent().getStringExtra("orderId");

        mBinding.tvWaitingFee.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        mBinding.tvWaitingFee.getPaint().setAntiAlias(true);//抗锯齿

        mBinding.mapView.showScaleControl(false);  // 设置比例尺是否可见（true 可见/false不可见）
        mBinding.mapView.showZoomControls(false);  // 设置缩放控件是否可见（true 可见/false不可见）
        View child = mBinding.mapView.getChildAt(1); // 找到百度LOGO控件对象
        if ((child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);  // 设置child这个控件是否可见（VISIBLE 可见/INVISIBLE不可见 /GONE 完全隐藏）
        }

        // 得到地图
        mBaiduMap = mBinding.mapView.getMap();

        requestNetData();

        //等待时长
        mBinding.tvWaitTimer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer ch) {
                waitTime++;
                ch.setText(FormatMiss(waitTime));

            }
        });

        //累计时长
        mBinding.tvCumulativeTimer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer ch) {
                cumulativeTime++;
                ch.setText(FormatMiss(cumulativeTime));

            }
        });

        //休息时长
        mBinding.tvRestTimer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer ch) {
                restTime++;
                ch.setText(FormatMiss(restTime));

            }
        });

        //干活时长
        mBinding.tvWorkTimer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer ch) {
                workTime++;
                ch.setText(FormatMiss(workTime));

            }
        });
    }

    // 将秒转化成小时分钟
    public String FormatMiss(int miss) {
        String hh = miss / 3600 > 9 ? miss / 3600 + "" : "0" + miss / 3600;
        String mm = (miss % 3600) / 60 > 9 ? (miss % 3600) / 60 + "" : "0" + (miss % 3600) / 60;
//        String ss = (miss % 3600) % 60 > 9 ? (miss % 3600) % 60 + "" : "0" + (miss % 3600) % 60;
        return hh + ":" + mm;
    }

    private void requestNetData() {

        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", authorization);
        map.put("orderId", orderId);

        mViewModel.getOrderPaymentDetailsData(map);
    }


    /**
     * 将毫秒转化为 分钟：秒 的格式
     *
     * @param millisecond 毫秒
     * @return
     */
    public String formatTime(long millisecond) {
        int minute;//分钟
        int second;//秒数
        minute = (int) ((millisecond / 1000) / 60);
        second = (int) ((millisecond / 1000) % 60);
        if (minute < 10) {
            if (second < 10) {
                return "0" + minute + ":" + "0" + second;
            } else {
                return "0" + minute + ":" + second;
            }
        } else {
            if (second < 10) {
                return minute + ":" + "0" + second;
            } else {
                return minute + ":" + second;
            }
        }
    }

    /**
     * 取消倒计时
     */
    public void timerCancel() {
        if (timer != null)
            timer.cancel();
    }

    /**
     * 开始倒计时
     */
    public void timerStart() {
        if (timer != null)
            timer.start();
    }


    @Override
    public void onResume() {
        mBinding.mapView.onResume();
        super.onResume();
    }

    @Override
    public void onPause() {
        mBinding.mapView.onPause();
        super.onPause();
    }

    @Override
    public void onDestroy() {
        mBinding.mapView.onDestroy();
        super.onDestroy();
    }


  /*  //安全中心
    @Override
    public void onSecurityCenter() {
        IntentManager.toSecurityCenterActivity(this);
    }*/

    //延时前往确认
    @Override
    public void onConfirm() {
        if (delayDetailsDialogFragment == null)
            delayDetailsDialogFragment = new DelayDetailsDialogFragment();
        delayDetailsDialogFragment.setDelayDetailsListener(()->{
            requestNetData();
        });
        delayDetailsDialogFragment.setData(orderPaymentDetailsBean);
        delayDetailsDialogFragment.show(getSupportFragmentManager());
    }

    //发送信息
    @Override
    public void onSendMessage(OrderPaymentDetailsBean data) {
        ToastUtils.showShort("发送信息");
    }

    //拨打电话
    @Override
    public void onPhone(OrderPaymentDetailsBean data) {
        PhoneUtils.dial(this, AEACCoder.decrypt(data.contactPhone));
    }

    //等候费
    @Override
    public void onWaitingFee() {
        IntentManager.toWaitingFeeActivity(this);
    }

    //报警
    @Override
    public void onPolice(String contactPhone) {
        ToastUtils.showShort("报警");
    }

    //客服
    @Override
    public void onCustomerService(OrderPaymentDetailsBean data) {
        PhoneUtils.dial(this, AEACCoder.decrypt(data.customerServicePhone));
    }

    //分享单子
    @Override
    public void onShareOrder() {
        ToastUtils.showShort("分享订单");
    }

    //取消单子
    @Override
    public void onCancelOrder() {
        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", authorization);
        map.put("orderId", orderId);
        map.put("userType", Constant.USER_TYPE);
        map.put("udid",  PhoneUtils.getUDID());

        mViewModel.cancelOrder(map);
    }

    //联系不上
    @Override
    public void onContactNo() {
        ToastUtils.showShort("联系不上");
    }


    //更换机佬
    @Override
    public void onChangeDriver() {
        ToastUtils.showShort("更换机佬");
    }

    //复制订单号
    @Override
    public void onCopyOrder(String orderId) {
        ClipboardManager myClipboard = (ClipboardManager) this.getSystemService(CLIPBOARD_SERVICE);
        ClipData myClip = ClipData.newPlainText("orderId", orderId);
        myClipboard.setPrimaryClip(myClip);
        ToastUtils.showShort("复制成功");
    }

    //确认完成
    @Override
    public void onDetermine() {
        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", authorization);
        map.put("orderId", orderId);
        mViewModel.determineOrderCompleteData(map);
    }

    //视频监控
    @Override
    public void onVideoSurveillance() {
        IntentManager.toVideoSurveillanceActivity(this);

    }

    @Override
    public void returnOrderDetailsData(OrderDetailsBean data) {

        if (data.status == 100) {
            finish();
        }

        mBinding.toolbar.setTitleText(data.title);
        orderPaymentDetailsBean.status = data.status;
        orderPaymentDetailsBean.distanceState = data.content;
        orderPaymentDetailsBean.waitState = data.waitState;
        orderPaymentDetailsBean.waitHint = data.waitHint;
        orderPaymentDetailsBean.toAddressState = data.toAddressState;
        orderPaymentDetailsBean.arriveState = data.arriveState;
        orderPaymentDetailsBean.timingTag = data.timingTag;
        orderPaymentDetailsBean.waitingFreeStartTime = data.waitingFreeStartTime;
        orderPaymentDetailsBean.cumulativeDurationHint = data.cumulativeDurationHint;
        orderPaymentDetailsBean.midwayRestHint = data.midwayRestHint;
        orderPaymentDetailsBean.ownerContent = data.ownerContent;
        orderPaymentDetailsBean.content = data.content;


        mBinding.setData(orderPaymentDetailsBean);

        mBaiduMap.clear();
        if (!TextUtils.isEmpty(data.latitude)) {
            setMapViewAddress(Double.parseDouble(data.latitude), Double.parseDouble(data.longitude));
            addMaker(Double.parseDouble(data.latitude), Double.parseDouble(data.longitude), data.statusHint);
        }


        if (data.timingTag == 1) {
            waitTime = (int) (System.currentTimeMillis() - TimeUtils.parsStringTimeLong(data.waitingFreeStartTime)) / 1000;
            mBinding.tvWaitTimer.start();
        }

        //0前往目的地   1到达目的地  2干活中  大于2休息中
        if (data.status == 0 || data.status == 1) {
            mBinding.rlBeforeWork.setVisibility(View.VISIBLE);
        } else {
            mBinding.rlBeforeWork.setVisibility(View.GONE);
            mBinding.tvWaitTimer.stop();
            mBinding.rlAfterWork.setVisibility(View.VISIBLE);

            //累计时长
            cumulativeTime = data.cumulativeDuration * 60;
            mBinding.tvCumulativeTimer.start();

            if (data.status > 2 && data.status != 100) {
                restTime = (int) (System.currentTimeMillis() - TimeUtils.parsStringTimeLong(data.lastOperateTime)) / 1000;
            }

            //休息时长
            restTime = restTime + data.midwayRest * 60;
            mBinding.tvRestTimer.start();

            //干活时间
            workTime = cumulativeTime - restTime;

            mBinding.tvWorkTimer.start();
            if (data.status == 2) {
                mBinding.tvRestTimer.stop();
            } else if (data.status > 2 && data.status != 100) {//休息中
                mBinding.tvWorkTimer.stop();
            }
        }
    }

    @Override
    public void returnDetermineOrderCompleteData() {
        IntentManager.toOrderEvaluateActivity(this);
    }

    @Override
    public void returnOrderPaymentDetailsData(OrderPaymentDetailsBean data) {
        restTime = 0;
        orderPaymentDetailsBean = data;
        if (orderPaymentDetailsBean.payTag == 0) {

            mBinding.toolbar.setTitleText(orderPaymentDetailsBean.ownerTitle);
            mBinding.setData(orderPaymentDetailsBean);
            getCountDownTimer();

            if (data.jobAddressList != null && data.jobAddressList.size() != 0)
                if (!TextUtils.isEmpty(data.jobAddressList.get(0).latitude)) {
                    setMapViewAddress(Double.parseDouble(data.jobAddressList.get(0).latitude), Double.parseDouble(data.jobAddressList.get(0).longitude));
                    addMaker(Double.parseDouble(data.jobAddressList.get(0).latitude), Double.parseDouble(data.jobAddressList.get(0).longitude), data.jobAddressList.get(0).address);
                }

        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("Authorization", authorization);
            map.put("orderId", orderId);
            mViewModel.getOrderDetailsData(map);
        }

    }

    public void getCountDownTimer() {
        long countDown = (System.currentTimeMillis() - TimeUtils.parsDataTimeLong(orderPaymentDetailsBean.pickUpTime));
        if (countDown >= 600000) {
            mBinding.llHead.setVisibility(View.GONE);
            timerCancel();
        } else {
            mBinding.llHead.setVisibility(View.VISIBLE);

            long newCountDown = 600000 - countDown;
            /**
             * 倒数计时器
             */
            timer = new CountDownTimer(newCountDown, 1000) {
                /**
                 * 固定间隔被调用,就是每隔countDownInterval会回调一次方法onTick
                 * @param millisUntilFinished
                 */
                @Override
                public void onTick(long millisUntilFinished) {
                    mBinding.tvTime.setText(formatTime(millisUntilFinished));
                }

                /**
                 * 倒计时完成时被调用
                 */
                @Override
                public void onFinish() {
                    mBinding.tvTime.setText("00:00");
                }
            };
            timerStart();
        }
    }

    @Override
    public void returnCancelOrder() {
        ToastUtils.showShort("取消成功");
        AppActivityManager.getAppActivityManager().returnToActivity(HomeActivity.class);
    }

    @Override
    protected boolean isRegisterEvent() {
        return true;
    }

    //推给师傅端推送的经纬度
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)//在ui线程执行
    public void onPushLatitudeLongitudeEvent(PushLatitudeLongitudeEvent event) {
        if (marker != null) marker.remove();

        String[] params = event.description.split("&&");
        System.out.println(params[0] + "收到订单信息20: " + params[1] + "===" + params[2] + "===" + params[3]);
        //112.885845收到订单信息20: 28.192739===12===49201878298263552

        String distance;

        //距离params[2]
        if (Integer.parseInt(params[2]) >= 1000) {
            distance = (Integer.parseInt(params[2]) / 1000) + "公里";
        } else {
            distance = params[2] + "米";
        }

        if (orderPaymentDetailsBean != null && !TextUtils.isEmpty(orderPaymentDetailsBean.ownerContent)) {
            distance = orderPaymentDetailsBean.ownerContent + distance;
        }

        mBinding.tvTitle.setText(distance);

        LatLng point = new LatLng(Double.parseDouble(params[1]), Double.parseDouble(params[0]));//坐标参数（纬度，经度）
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.ic_current_location);//自定义marker点图片

        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);
        marker = (Marker) mBaiduMap.addOverlay(option);//将marker添加到地图，并获取该marker点对象
    }

    //推送师傅干活的过程
    @Subscribe(threadMode = ThreadMode.MAIN)//在ui线程执行
    public void onPushWorkingProcessEvent(PushWorkingProcessEvent event) {
        MessageBody messageInfo = JSONObject.parseObject(event.content, MessageBody.class);
        if (String.valueOf(messageInfo.orderId).equals(orderId)) {
            requestNetData();
        }
    }


    public void setMapViewAddress(double latitude, double longitude) {
        LatLng ll = new LatLng(latitude, longitude);
        mapBuild = new MapStatus.Builder()
                .target(ll)
                .zoom(18f)
                .build();
        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mapBuild);
        //改变地图状态
        mBaiduMap.animateMapStatus(mMapStatusUpdate);
    }

    public void addMaker(double longitude, double latitude, String statusHint) {

        //定义Maker坐标点
        LatLng point = new LatLng(longitude, latitude);
        View view = View.inflate(OrderDetailsActivity.this, R.layout.view_marker_order_details, null);
        TextView tvStatusHint = view.findViewById(R.id.tv_status_hint);
        tvStatusHint.setText(statusHint);
        //构建Marker图标
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions options = new MarkerOptions()
                .position(point)
                .icon(BitmapDescriptorFactory.fromBitmap(getViewBitmap(view)));
        //在地图上添加Marker，并显示
        mBaiduMap.addOverlay(options);
    }

    private Bitmap getViewBitmap(View addViewContent) {

        addViewContent.setDrawingCacheEnabled(true);
        addViewContent.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        addViewContent.layout(0, 0,
                addViewContent.getMeasuredWidth(),
                addViewContent.getMeasuredHeight());
        addViewContent.buildDrawingCache();

        Bitmap cacheBitmap = addViewContent.getDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

        return bitmap;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOrderDetailsCancelEvent(OrderDetailsCancelEvent event) {
        MessageBody messageInfo = JSONObject.parseObject(event.content, MessageBody.class);
        if (String.valueOf(messageInfo.orderId).equals(orderId)) {
            ToastUtils.showShort("客户取消订单了");
            finish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOrderDelayEvent(OrderDelayEvent event) {
        MessageBody messageInfo = JSONObject.parseObject(event.content, MessageBody.class);
        if (String.valueOf(messageInfo.orderId).equals(orderId)) {
            requestNetData();
        }
    }
}
